package com.demo.accessibilitykeeper;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 屏幕遮罩服务
 * 功能：在屏幕上显示纯黑色遮罩，阻止所有触摸操作
 */
public class ScreenMaskService extends Service {
    private static final String TAG = "ScreenMaskService";
    
    private WindowManager windowManager;
    private View maskView;
    private View statusBarMask;
    private View notificationPanelMask;
    private boolean isMaskVisible = false;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "ScreenMaskService created");
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        
        // 启动前台服务
        startForegroundService();
        
        // 检查是否需要在启动时自动显示遮罩
        checkAndStartPersistentMask();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent != null ? intent.getStringExtra("action") : null;
        
        if ("show_mask".equals(action)) {
            showMask();
        } else if ("hide_mask".equals(action)) {
            hideMask();
        } else if ("toggle_mask".equals(action)) {
            toggleMask();
        } else if ("start_persistent_mask".equals(action)) {
            startPersistentMask();
        } else if ("stop_persistent_mask".equals(action)) {
            stopPersistentMask();
        }
        
        return START_STICKY;
    }
    
    /**
     * 显示屏幕遮罩
     */
    public void showMask() {
        if (isMaskVisible) {
            Log.d(TAG, "Mask already visible");
            return;
        }
        
        try {
            // 创建纯黑色遮罩视图
            maskView = new View(this);
            maskView.setBackgroundColor(0xFF000000); // 纯黑色
            maskView.setClickable(true);
            maskView.setFocusable(true);
            
            // 设置触摸事件拦截，阻止状态栏和通知栏下滑
            maskView.setOnTouchListener((v, event) -> {
                // 拦截所有触摸事件，包括状态栏和通知栏下滑
                Log.d(TAG, "🎭 MASK_TOUCH_INTERCEPTED - Blocking all touch events including status bar and notification panel");
                
                // 特别处理通知栏区域的下滑手势
                if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
                    float y = event.getY();
                    // 如果触摸点在屏幕顶部区域（通知栏区域），强制拦截
                    if (y < 200) { // 屏幕顶部200像素区域
                        Log.d(TAG, "🚫 NOTIFICATION_PANEL_TOUCH_BLOCKED - Blocking notification panel touch");
                        return true;
                    }
                }
                
                return true; // 消费所有触摸事件
            });
            
            // 设置窗口参数
            WindowManager.LayoutParams params = new WindowManager.LayoutParams();
            
            // 设置窗口类型
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                params.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            
            // 设置窗口标志 - 增强遮罩效果，完全阻止通知栏
            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                         WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                         WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                         WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                         WindowManager.LayoutParams.FLAG_FULLSCREEN |
                         WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                         WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                         WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS |
                         WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED |
                         WindowManager.LayoutParams.FLAG_LAYOUT_ATTACHED_IN_DECOR |
                         WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            
            // 设置窗口格式
            params.format = PixelFormat.TRANSLUCENT;
            
            // 设置窗口大小和位置 - 覆盖整个屏幕包括状态栏
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.MATCH_PARENT;
            params.gravity = Gravity.TOP | Gravity.LEFT;
            
            // 设置状态栏遮罩
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                params.x = 0;
                params.y = 0;
            }
            
            // 添加到窗口管理器
            windowManager.addView(maskView, params);
            
            // 创建额外的状态栏遮罩层
            createStatusBarMask();
            
            // 创建通知栏遮罩层
            createNotificationPanelMask();
            
            isMaskVisible = true;
            
            Log.d(TAG, "✅ Screen mask displayed successfully");
            Toast.makeText(this, "屏幕遮罩已激活", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Failed to show screen mask", e);
            Toast.makeText(this, "显示遮罩失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 隐藏屏幕遮罩
     */
    public void hideMask() {
        if (!isMaskVisible) {
            Log.d(TAG, "Mask not visible");
            return;
        }
        
        try {
            if (maskView != null && windowManager != null) {
                windowManager.removeView(maskView);
                maskView = null;
            }
            
            // 移除状态栏遮罩
            removeStatusBarMask();
            
            // 移除通知栏遮罩
            removeNotificationPanelMask();
            
            isMaskVisible = false;
            
            Log.d(TAG, "✅ Screen mask hidden successfully");
            Toast.makeText(this, "屏幕遮罩已关闭", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ Failed to hide screen mask", e);
            Toast.makeText(this, "隐藏遮罩失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 切换遮罩状态
     */
    public void toggleMask() {
        if (isMaskVisible) {
            hideMask();
        } else {
            showMask();
        }
    }
    
    /**
     * 检查遮罩是否可见
     */
    public boolean isMaskVisible() {
        return isMaskVisible;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "ScreenMaskService destroyed");
        
        // 清理遮罩
        if (isMaskVisible) {
            hideMask();
        }
    }
    
    /**
     * 创建状态栏遮罩层
     */
    private void createStatusBarMask() {
        try {
            Log.d(TAG, "🔧 CREATING_STATUS_BAR_MASK");
            
            // 创建状态栏遮罩视图
            statusBarMask = new View(this);
            statusBarMask.setBackgroundColor(0xFF000000); // 纯黑色
            statusBarMask.setClickable(true);
            statusBarMask.setFocusable(true);
            
            // 设置状态栏遮罩的触摸事件拦截
            statusBarMask.setOnTouchListener((v, event) -> {
                Log.d(TAG, "🎭 STATUS_BAR_TOUCH_INTERCEPTED - Blocking status bar interactions");
                return true; // 消费所有触摸事件，阻止状态栏下滑
            });
            
            // 设置状态栏遮罩窗口参数
            WindowManager.LayoutParams statusBarParams = new WindowManager.LayoutParams();
            
            // 设置窗口类型
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                statusBarParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                statusBarParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            
            // 设置状态栏遮罩标志
            statusBarParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                                   WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                                   WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                                   WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                                   WindowManager.LayoutParams.FLAG_FULLSCREEN |
                                   WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                                   WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                                   WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS |
                                   WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
            
            // 设置窗口格式
            statusBarParams.format = PixelFormat.TRANSLUCENT;
            
            // 设置状态栏遮罩大小和位置
            statusBarParams.width = WindowManager.LayoutParams.MATCH_PARENT;
            statusBarParams.height = getStatusBarHeight(); // 状态栏高度
            statusBarParams.gravity = Gravity.TOP | Gravity.LEFT;
            statusBarParams.x = 0;
            statusBarParams.y = 0;
            
            // 添加到窗口管理器
            windowManager.addView(statusBarMask, statusBarParams);
            
            Log.d(TAG, "✅ STATUS_BAR_MASK_CREATED_SUCCESSFULLY");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CREATING_STATUS_BAR_MASK", e);
        }
    }
    
    /**
     * 获取状态栏高度
     */
    private int getStatusBarHeight() {
        try {
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                return getResources().getDimensionPixelSize(resourceId);
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_GETTING_STATUS_BAR_HEIGHT", e);
        }
        
        // 默认状态栏高度
        return 24 * getResources().getDisplayMetrics().densityDpi / 160; // 24dp转换为px
    }
    
    /**
     * 移除状态栏遮罩层
     */
    private void removeStatusBarMask() {
        try {
            if (statusBarMask != null && windowManager != null) {
                Log.d(TAG, "🔧 REMOVING_STATUS_BAR_MASK");
                windowManager.removeView(statusBarMask);
                statusBarMask = null;
                Log.d(TAG, "✅ STATUS_BAR_MASK_REMOVED_SUCCESSFULLY");
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_REMOVING_STATUS_BAR_MASK", e);
        }
    }
    
    /**
     * 创建通知栏遮罩层
     */
    private void createNotificationPanelMask() {
        try {
            Log.d(TAG, "🔧 CREATING_NOTIFICATION_PANEL_MASK");
            
            // 创建通知栏遮罩视图
            notificationPanelMask = new View(this);
            notificationPanelMask.setBackgroundColor(0xFF000000); // 纯黑色
            notificationPanelMask.setClickable(true);
            notificationPanelMask.setFocusable(true);
            
            // 设置通知栏遮罩的触摸事件拦截
            notificationPanelMask.setOnTouchListener((v, event) -> {
                Log.d(TAG, "🎭 NOTIFICATION_PANEL_TOUCH_INTERCEPTED - Blocking notification panel interactions");
                return true; // 消费所有触摸事件，阻止通知栏下拉
            });
            
            // 设置通知栏遮罩窗口参数
            WindowManager.LayoutParams notificationPanelParams = new WindowManager.LayoutParams();
            
            // 设置窗口类型
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notificationPanelParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                notificationPanelParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            
            // 设置通知栏遮罩标志
            notificationPanelParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                                         WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                                         WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                                         WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                                         WindowManager.LayoutParams.FLAG_FULLSCREEN |
                                         WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                                         WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                                         WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS |
                                         WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED |
                                         WindowManager.LayoutParams.FLAG_LAYOUT_ATTACHED_IN_DECOR |
                                         WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            
            // 设置窗口格式
            notificationPanelParams.format = PixelFormat.TRANSLUCENT;
            
            // 设置通知栏遮罩大小和位置
            notificationPanelParams.width = WindowManager.LayoutParams.MATCH_PARENT;
            notificationPanelParams.height = getNotificationPanelHeight(); // 通知栏高度
            notificationPanelParams.gravity = Gravity.TOP | Gravity.LEFT;
            notificationPanelParams.x = 0;
            notificationPanelParams.y = 0;
            
            // 添加到窗口管理器
            windowManager.addView(notificationPanelMask, notificationPanelParams);
            
            Log.d(TAG, "✅ NOTIFICATION_PANEL_MASK_CREATED_SUCCESSFULLY");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CREATING_NOTIFICATION_PANEL_MASK", e);
        }
    }
    
    /**
     * 获取通知栏高度
     */
    private int getNotificationPanelHeight() {
        try {
            // 获取屏幕高度
            android.util.DisplayMetrics metrics = getResources().getDisplayMetrics();
            int screenHeight = metrics.heightPixels;
            
            // 通知栏高度通常是屏幕高度的1/3到1/2
            return screenHeight / 3;
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_GETTING_NOTIFICATION_PANEL_HEIGHT", e);
            return 400; // 默认通知栏高度
        }
    }
    
    /**
     * 移除通知栏遮罩层
     */
    private void removeNotificationPanelMask() {
        try {
            if (notificationPanelMask != null && windowManager != null) {
                Log.d(TAG, "🔧 REMOVING_NOTIFICATION_PANEL_MASK");
                windowManager.removeView(notificationPanelMask);
                notificationPanelMask = null;
                Log.d(TAG, "✅ NOTIFICATION_PANEL_MASK_REMOVED_SUCCESSFULLY");
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_REMOVING_NOTIFICATION_PANEL_MASK", e);
        }
    }
    
    /**
     * 检查并启动持续遮罩
     */
    private void checkAndStartPersistentMask() {
        try {
            Log.d(TAG, "🔧 CHECKING_PERSISTENT_MASK_STATUS");
            
            // 检查持续遮罩是否已启用
            SharedPreferences prefs = getSharedPreferences("persistent_mask_prefs", MODE_PRIVATE);
            boolean isPersistentMaskEnabled = prefs.getBoolean("persistent_mask_enabled", false);
            
            if (isPersistentMaskEnabled) {
                Log.d(TAG, "✅ PERSISTENT_MASK_ENABLED - Starting persistent mask automatically");
                startPersistentMask();
            } else {
                Log.d(TAG, "❌ PERSISTENT_MASK_DISABLED - Skipping persistent mask start");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_PERSISTENT_MASK_STATUS", e);
        }
    }
    
    /**
     * 启动持续遮罩
     */
    private void startPersistentMask() {
        try {
            Log.d(TAG, "🎭 STARTING_PERSISTENT_MASK");
            
            // 显示遮罩
            showMask();
            
            // 保存持续遮罩状态
            SharedPreferences prefs = getSharedPreferences("persistent_mask_prefs", MODE_PRIVATE);
            prefs.edit().putBoolean("persistent_mask_enabled", true).apply();
            
            Log.d(TAG, "✅ PERSISTENT_MASK_STARTED_SUCCESSFULLY");
            Toast.makeText(this, "持续遮罩已启动，重启手机才能解除", Toast.LENGTH_LONG).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_PERSISTENT_MASK", e);
        }
    }
    
    /**
     * 停止持续遮罩
     */
    private void stopPersistentMask() {
        try {
            Log.d(TAG, "🎭 STOPPING_PERSISTENT_MASK");
            
            // 隐藏遮罩
            hideMask();
            
            // 保存持续遮罩状态
            SharedPreferences prefs = getSharedPreferences("persistent_mask_prefs", MODE_PRIVATE);
            prefs.edit().putBoolean("persistent_mask_enabled", false).apply();
            
            Log.d(TAG, "✅ PERSISTENT_MASK_STOPPED_SUCCESSFULLY");
            Toast.makeText(this, "持续遮罩已停止", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STOPPING_PERSISTENT_MASK", e);
        }
    }
    
    /**
     * 启动前台服务
     */
    private void startForegroundService() {
        try {
            Log.d(TAG, "🔧 STARTING_FOREGROUND_SERVICE");
            
            // 创建通知渠道
            createNotificationChannel();
            
            // 创建通知
            Notification notification = createNotification();
            
            // 启动前台服务
            startForeground(1, notification);
            
            Log.d(TAG, "✅ FOREGROUND_SERVICE_STARTED_SUCCESSFULLY");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_FOREGROUND_SERVICE", e);
        }
    }
    
    /**
     * 创建通知渠道
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                "screen_mask_channel",
                "屏幕遮罩服务",
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("持续运行的屏幕遮罩服务");
            channel.setShowBadge(false);
            channel.setSound(null, null);
            channel.enableLights(false);
            channel.enableVibration(false);
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
    
    /**
     * 创建通知
     */
    private Notification createNotification() {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, intent, 
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0
        );
        
        Notification.Builder builder = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("screen_mask_channel");
        }
        
        return builder
            .setContentTitle("屏幕遮罩服务")
            .setContentText("持续运行的屏幕遮罩服务，重启手机才能解除")
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setAutoCancel(false)
            .setPriority(Notification.PRIORITY_LOW)
            .build();
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
